import React, { useEffect, useState, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import { usePagePreloader } from '../hooks/usePagePreloader';

interface BackgroundPageManagerProps {
  children: React.ReactNode;
}

const BackgroundPageManager: React.FC<BackgroundPageManagerProps> = ({ children }) => {
  const location = useLocation();
  const { getBackgroundPages, moveToBackground, activateCurrentPage } = usePagePreloader();
  const [backgroundPages, setBackgroundPages] = useState<string[]>([]);
  const previousPathRef = useRef<string>('');

  useEffect(() => {
    // 激活当前页面
    activateCurrentPage(location.pathname);
    
    // 当路径变化时，将之前的页面移到后台
    if (previousPathRef.current && previousPathRef.current !== location.pathname) {
      moveToBackground(previousPathRef.current);
    }
    
    previousPathRef.current = location.pathname;
    
    // 更新后台页面列表
    setBackgroundPages(getBackgroundPages());
  }, [location.pathname, moveToBackground, getBackgroundPages, activateCurrentPage]);

  // 定期更新后台页面状态
  useEffect(() => {
    const interval = setInterval(() => {
      setBackgroundPages(getBackgroundPages());
    }, 1000);

    return () => clearInterval(interval);
  }, [getBackgroundPages]);

  return (
    <>
      {children}
      {/* 在开发模式下显示后台页面信息 */}
      {process.env.NODE_ENV === 'development' && backgroundPages.length > 0 && (
        <div style={{
          position: 'fixed',
          bottom: '10px',
          right: '10px',
          background: 'rgba(0, 0, 0, 0.8)',
          color: 'white',
          padding: '10px',
          borderRadius: '5px',
          fontSize: '12px',
          zIndex: 9999,
          maxWidth: '200px'
        }}>
          <div style={{ fontWeight: 'bold', marginBottom: '5px' }}>
            后台页面 ({backgroundPages.length})
          </div>
          {backgroundPages.map((path, index) => (
            <div key={index} style={{ marginBottom: '2px' }}>
              {path}
            </div>
          ))}
        </div>
      )}
    </>
  );
};

export default BackgroundPageManager;
